import * as Koa from "koa";
import * as route from "koa-route";
import * as cors from "@koa/cors";
import * as crypto from "crypto";
import * as xmlParser from "koa-xml-body";
import ConsoleWrapper from "./utils/ConsoleWrapper";
import { WX_TOKEN, WX_APPID, WX_APPSECRET, WX_AESKEY } from "./env";
import Wechat from "../sdk/lib";
import handleMsg from "./messageHandler";

const app = new Koa();
const wx = new Wechat.OfficialAccount({
    appid: WX_APPID,
    secret: WX_APPSECRET,
    token: WX_TOKEN,
    aesKey: WX_AESKEY,
    server: "koa"
});

// test
// const us = wx.getService("qrcode");
// us.temporary("https://www.baidu.com").then(resp => {
//     console.log(resp);
//     console.log(us.url(resp.ticket));
// });

handleMsg(wx, app);

// x-response-time
app.use(async (ctx, next) => {
    const start = Date.now();
    await next();
    const ms = Date.now() - start;
    ctx.set("X-Response-Time", `${ms}ms`);
});

// cors
app.use(cors({ credentials: true }));

// 微信开发服务器验证
// https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421135319
app.use(
    route.get("/", async ctx => {
        ConsoleWrapper.log(ctx.url);
        try {
            const { query } = ctx;
            const { signature, timestamp, nonce, echostr } = query;
            const text = crypto
                .createHash("sha1")
                .update([WX_TOKEN, timestamp, nonce].sort().join(""))
                .digest("hex");

            if (text === signature) {
                ctx.status = 200;
                ctx.body = echostr;
            } else {
                throw new Error("Verify failed");
            }
        } catch (err) {
            ctx.throw(err.message || err.toString(), 500);
        }
    })
);

// 接收消息
app.use(
    route.post("/", async ctx => {
        ConsoleWrapper.log(ctx.url);
        ConsoleWrapper.log(ctx.request.body.xml);
        ctx.status = 200;
        ctx.body = "";
    })
);

app.on("error", err => {
    ConsoleWrapper.error(err);
});

app.listen(8801, "127.0.0.1", () => {
    ConsoleWrapper.log("Server Is Listening at http://127.0.0.1:8801");
});

process.on("exit", code => {
    ConsoleWrapper.log(`Process about to exit with code: ${code}`);
});
